package com.ytjj.qmyx.admin.service.channelLabel.impl;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.ytjj.common.api.CommonPage;
import com.ytjj.qmyx.admin.dao.channel.ChannelLabelDao;
import com.ytjj.qmyx.admin.mapper.ChannelLabelAutoDetailMapper;
import com.ytjj.qmyx.admin.mapper.ChannelLabelAutoMapper;
import com.ytjj.qmyx.admin.mapper.ChannelLabelMapper;
import com.ytjj.qmyx.admin.mapper.ChannelProductLabelMapper;
import com.ytjj.qmyx.admin.model.*;
import com.ytjj.qmyx.admin.model.request.channel.ChannelLabelRequest;
import com.ytjj.qmyx.admin.model.request.channel.ChannelProductLabelEntity;
import com.ytjj.qmyx.admin.model.request.channel.ChannelProductLabelRequest;
import com.ytjj.qmyx.admin.model.response.channel.ChannelLabelDetailEntity;
import com.ytjj.qmyx.admin.model.response.channel.ChannelLabelResponse;
import com.ytjj.qmyx.admin.service.channelLabel.ChannelLabelService;
import com.ytjj.qmyx.admin.utils.DateUtils;
import com.ytjj.qmyx.admin.utils.UserUtil;
import com.ytjj.qmyx.mall.mapper.ProductMapper;
import com.ytjj.qmyx.mall.model.Product;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;

@Service
public class ChannelLabelServiceImpl implements ChannelLabelService {

    @Autowired
    private ChannelLabelMapper channelLabelMapper;
    @Autowired
    private ChannelLabelAutoMapper channelLabelAutoMapper;
    @Autowired
    private ChannelLabelAutoDetailMapper channelLabelAutoDetailMapper;
    @Autowired
    private ChannelLabelDao channelLabelDao;
    @Autowired
    private ChannelProductLabelMapper channelProductLabelMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public CommonPage<ChannelLabelResponse> findList(ChannelLabelRequest channelLabelRequest) {
        PageHelper.startPage(channelLabelRequest.getPageNum(),channelLabelRequest.getPageSize());
        List<ChannelLabelResponse> list = channelLabelDao.findList(channelLabelRequest);
        return CommonPage.restPage(list);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(ChannelLabelRequest request) {

        //保存标签基本信息
        ChannelLabel channelLabel = new ChannelLabel();
        BeanUtils.copyProperties(request,channelLabel);
        channelLabel.setCreateUser(UserUtil.getAdminId());
        channelLabelMapper.insertSelective(channelLabel);

        //保存自动打标相关信息
        if (request.getType() == 2){
            request.getChannelLabelAuto().setLabelId(channelLabel.getId());
            channelLabelAutoMapper.insertSelective(request.getChannelLabelAuto());

            //分类数据结构转字符串
            List<List<Integer>> categoryList = request.getChannelLabelAutoDetail().getProductCategoryList();
            request.getChannelLabelAutoDetail().setProductCategory(listToStr(categoryList));
            request.getChannelLabelAutoDetail().setLabelId(channelLabel.getId());
            channelLabelAutoDetailMapper.insertSelective(request.getChannelLabelAutoDetail());
        }

    }

    private String listToStr(List<List<Integer>> categoryList){
        if (CollectionUtils.isNotEmpty(categoryList)){
            List<String> list = Lists.newArrayList();
            for (List<Integer> categorys:categoryList){
                String item = StringUtils.join(categorys,"-");
                list.add(item);
            }
            String productCategory=StringUtils.join(list,",");
            return productCategory;
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(ChannelLabelRequest request) {
        ChannelLabel channelLabel = new ChannelLabel();
        BeanUtils.copyProperties(request,channelLabel);
        channelLabelMapper.updateByPrimaryKeySelective(channelLabel);

        //设置自动打标的
        if (request.getChannelLabelAuto()!=null && request.getType()==2){
            ChannelLabelAuto channelLabelAuto = channelLabelAutoMapper.selectByPrimaryKey(request.getId());
            if (channelLabelAuto!=null){
                request.getChannelLabelAuto().setLabelId(request.getId());
                channelLabelAutoMapper.updateByPrimaryKeySelective(request.getChannelLabelAuto());

                //分类数据结构转字符串
                List<List<Integer>> categoryList = request.getChannelLabelAutoDetail().getProductCategoryList();
                request.getChannelLabelAutoDetail().setProductCategory(listToStr(categoryList));
                request.getChannelLabelAutoDetail().setLabelId(request.getId());
                channelLabelAutoDetailMapper.updateByPrimaryKeySelective(request.getChannelLabelAutoDetail());
            }else{
                //保存自动打标相关信息
                request.getChannelLabelAuto().setLabelId(channelLabel.getId());
                channelLabelAutoMapper.insertSelective(request.getChannelLabelAuto());

                //分类数据结构转字符串
                List<List<Integer>> categoryList = request.getChannelLabelAutoDetail().getProductCategoryList();
                request.getChannelLabelAutoDetail().setProductCategory(listToStr(categoryList));
                request.getChannelLabelAutoDetail().setLabelId(channelLabel.getId());
                channelLabelAutoDetailMapper.insertSelective(request.getChannelLabelAutoDetail());
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Integer id) {
        channelLabelMapper.deleteByPrimaryKey(id);
        channelLabelAutoMapper.deleteByPrimaryKey(id);
        channelLabelAutoDetailMapper.deleteByPrimaryKey(id);
    }

    @Override
    public ChannelLabelResponse findDetail(Integer id) {
        ChannelLabelResponse response = new ChannelLabelResponse();
        ChannelLabel channelLabel = channelLabelMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(channelLabel,response);
        if (channelLabel.getType() == 2){
            ChannelLabelAuto channelLabelAuto = channelLabelAutoMapper.selectByPrimaryKey(id);
            ChannelLabelAutoDetail channelLabelAutoDetail = channelLabelAutoDetailMapper.selectByPrimaryKey(id);
            if (StringUtils.isNotBlank(channelLabelAutoDetail.getProductCategory())){
                //字符串转list
                List<List<Integer>> productCategoryList = Lists.newArrayList();
                String[] strArr = channelLabelAutoDetail.getProductCategory().split(",");
                for (int i=0;i<strArr.length;i++){
                    String[] item = strArr[i].split("-");
                    List<Integer> list = Lists.newArrayList();
                    for (int j=0;j<item.length;j++){
                        int categoryId = Integer.parseInt(item[j]);
                        list.add(categoryId);
                    }
                    productCategoryList.add(list);
                }
                channelLabelAutoDetail.setProductCategoryList(productCategoryList);
            }
            response.setChannelLabelAuto(channelLabelAuto);
            response.setChannelLabelAutoDetail(channelLabelAutoDetail);
        }
        return response;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void setProductLabel(ChannelProductLabelRequest request) {
        List<Integer> productIds = request.getProductIds();
        List<Integer> labelIds = request.getLabelIds();

        List<ChannelProductLabelEntity> list = Lists.newArrayList();
        Integer adminId = UserUtil.getAdminId();
        for (Integer productId:productIds){
            for (Integer labelId:labelIds){
                ChannelProductLabelEntity entity = new ChannelProductLabelEntity();
                entity.setProductId(productId);
                entity.setLabelId(labelId);
                entity.setChannel(request.getChannel());
                entity.setAdminId(adminId);
                list.add(entity);
            }
        }
        int count = channelLabelDao.batchInsertProductLabel(list);
        Assert.isTrue(count>0,"添加标签失败");
        //删除没有勾选的标签
        channelLabelDao.delProductLabel(request);
    }

    @Override
    public void delProductLabel(ChannelProductLabelRequest request) {
        ChannelProductLabelExample example = new ChannelProductLabelExample();
        example.createCriteria().andChannelEqualTo(request.getChannel()).andProductIdIn(request.getProductIds());
        channelProductLabelMapper.deleteByExample(example);
    }

    @Override
    public void handleChannelLabel(Product product) {
        //查出所有自动打标的标签
        List<ChannelLabelDetailEntity> allLabel = channelLabelDao.findLabelAutoDetail(product.getPlatformData());
        if (CollectionUtils.isNotEmpty(allLabel)){
            for (ChannelLabelDetailEntity entity:allLabel){
                //此商品是否已打过此标签
                int count = channelLabelDao.countByProductAndLabelId(product.getPlatformData(),product.getId(),entity.getLabelId());
                int categoryCheck =entity.getProductCategoryCheck();
                int brandNameCheck = entity.getBrandNameCheck();
                int activityCheck = entity.getActivityCheck();
                int launchDateCheck = entity.getLaunchDateCheck();
                int launchDayCheck = entity.getLaunchDayCheck();
                int buyNumCheck = entity.getBuyNumCheck();
                int productStockCheck = entity.getProductStockCheck();
                int totalChekck = categoryCheck+brandNameCheck+activityCheck+launchDayCheck+buyNumCheck+productStockCheck;
                if (totalChekck == 0){
                    continue;
                }

                boolean checkProductCategory = (categoryCheck==1?checkProductCategory(entity,product):false);
                boolean checkBrandName = (brandNameCheck==1?checkBrandName(entity,product):false);
                boolean checkActivity = (activityCheck==1?checkActivity(entity,product):false);
                boolean checkLaunchDate = (launchDateCheck==1?checkLaunchDate(entity,product):false);
                boolean checkLaunchDay = (launchDayCheck==1?checkLaunchDay(entity,product):false);
                boolean checkBuyNum = (buyNumCheck==1?checkBuyNum(entity,product):false);
                boolean checkProductStock = (productStockCheck==1?checkProductStock(entity,product):false);

                List<Boolean> list = Lists.newArrayList();
                list.add(checkProductCategory);
                list.add(checkBrandName);
                list.add(checkActivity);
                list.add(checkLaunchDate);
                list.add(checkLaunchDay);
                list.add(checkBuyNum);
                list.add(checkProductStock);

                if (count>0){
                    //满足条件 就删除
                    if (entity.getType() == 1){
                        long falseCount = list.stream().filter(x->x==false).count();
                        if (falseCount == totalChekck){
                            delProductLabel(product,entity.getLabelId());
                        }
                    }
                    if (entity.getType() == 2 && list.contains(true)){
                        delProductLabel(product,entity.getLabelId());
                    }
                }else{
                    //满足条件 添加标签
                    if (entity.getType() == 1 && list.contains(true)){
                        addProductLabel(product,entity.getLabelId());
                    }
                    if (entity.getType() == 2){
                        long trueCount = list.stream().filter(x->x==true).count();
                        if (trueCount == totalChekck){
                            addProductLabel(product,entity.getLabelId());
                        }
                    }
                }
            }
        }

    }

    public boolean checkProductCategory(ChannelLabelDetailEntity entity,Product product){
        String category = entity.getProductCategory();
        String[] groupArray = category.split(",");
        for (int i=0;i<groupArray.length;i++){
            String[] categoryIdArray = groupArray[i].split("-");
            if (categoryIdArray.length == 3){
                Integer bottomCategoryId =Integer.parseInt(categoryIdArray[2]);
                //三级分类id一样就可以打标签了
                if (bottomCategoryId.equals(product.getBottomCategoryId())){
                    return true;
                }
            }
            if (categoryIdArray.length == 2){
                //二级分类id一样就可以打标签了
                Integer categoryId =Integer.parseInt(categoryIdArray[1]);
                if (categoryId.equals(product.getCategoryId())){
                    return true;
                }
            }
            if (categoryIdArray.length == 1){
                Integer topCategoryId =Integer.parseInt(categoryIdArray[0]);
                //一级级分类id一样就可以打标签了
                if (topCategoryId.equals(product.getTopCategoryId())){
                    return true;
                }
            }
        }
        return false;
    }

    public boolean checkBrandName(ChannelLabelDetailEntity entity,Product product){
        String brand = entity.getBrandName();
        if (StringUtils.isNotBlank(brand)){
            String[] brandIds = brand.split(",");
            for (int i=0;i<brandIds.length;i++){
                Integer brandId = Integer.parseInt(brandIds[i]);
                if (brandId.equals(product.getBrandId())){
                    return true;
                }
            }
        }
        return false;
    }

    public boolean checkActivity(ChannelLabelDetailEntity entity,Product product){
        String activity = entity.getActivity();
        if (StringUtils.isNotBlank(activity)){
            String[] activityArray = activity.split(",");
            for (int i=0;i<activityArray.length;i++){
                if (activityArray[i].equals(product.getActivityType())){
                    return true;
                }
            }
        }
        return false;
    }

    public boolean checkLaunchDate(ChannelLabelDetailEntity entity,Product product){
        Date launchDateStarte = entity.getLaunchDateStart();
        Date launchDateEnd = entity.getLaunchDateEnd();
        Date upTime = product.getUpdateTime();
        if (upTime != null && launchDateStarte!=null && launchDateEnd!=null){
            if (launchDateStarte.getTime()<=upTime.getTime() && upTime.getTime()<=launchDateEnd.getTime()){
                return true;
            }
        }
        return false;
    }

    public boolean checkLaunchDay(ChannelLabelDetailEntity entity,Product product){
        Integer launchDayStart = entity.getLaunchDayStart();
        Integer launchDayEnd = entity.getLaunchDayEnd();
        Date upTime = product.getUpdateTime();
        if (launchDayStart!=null && launchDayEnd!=null && upTime!=null){
            int day = DateUtils.differentDaysByMillisecond(upTime,new Date());
            if (day>=launchDayStart && day<=launchDayEnd){
                return true;
            }
        }
        return false;
    }

    public boolean checkBuyNum(ChannelLabelDetailEntity entity,Product product){
        Integer buyNumMin = entity.getBuyNumMin();
        Integer entityBuyNumMax = entity.getBuyNumMax();
        Integer volume = product.getVolume();
        if (buyNumMin!=null && entityBuyNumMax!=null && volume!=null){
            if (volume>=buyNumMin && volume<=entityBuyNumMax){
                return true;
            }
        }
        return false;
    }

    public boolean checkProductStock(ChannelLabelDetailEntity entity,Product product){
        Integer stockMin = entity.getProductStockMin();
        Integer stockMax = entity.getProductStockMax();
        Integer stock = product.getStock();
        if (stockMin!=null && stockMax!=null && stock!=null){
            if (stock>=stockMin && stock<=stockMax){
                return true;
            }
        }
        return false;
    }

    private void addProductLabel(Product product,Integer labelId){
        ChannelProductLabel record = new ChannelProductLabel();
        record.setChannel(product.getPlatformData());
        record.setProductId(product.getId());
        record.setLabelId(labelId);
        record.setAdminId(UserUtil.getAdminId());
        channelProductLabelMapper.insertSelective(record);
    }

    private void delProductLabel(Product product,Integer labelId){
        ChannelProductLabelExample example = new ChannelProductLabelExample();
        example.createCriteria().andChannelEqualTo(product.getPlatformData()).andProductIdEqualTo(product.getId())
        .andLabelIdEqualTo(labelId);
        channelProductLabelMapper.deleteByExample(example);
    }

    @Override
    public void testAutoLabel(Integer productId) {
        Product product = productMapper.selectByPrimaryKey(productId);
        handleChannelLabel(product);
    }

}
